package com.shujia

import scala.io.{BufferedSource, Source}

object Demo30Score {
  def main(args: Array[String]): Unit = {
    /**
     * 3、统计每个学生的总分
     */

    //读取数据
    val bufferedSource: BufferedSource = Source.fromFile("scala/data/score.txt")
    val lines: List[String] = bufferedSource.getLines().toList

    //解析数据
    val scores: List[(String, Double)] = lines
      .map(line => {
        val split: Array[String] = line.split(",")
        val id: String = split(0)
        val score: Double = split(2).toDouble
        (id, score)
      })

    //按照学号进行分组
    val groupBy: Map[String, List[(String, Double)]] = scores
      .groupBy {
        //下划线的作用是占位
        case (id, _) => id
      }

    //统计总分
    val sumScores: Map[String, Double] = groupBy
      .map {
        case (id: String, scoList: List[(String, Double)]) =>
          //取出分数，计算总分
          val sumScore: Double = scoList
            .map { case (_, score) => score }
            .sum
          //返回结果
          (id, sumScore)
      }

    sumScores.foreach(println)
  }

}
